﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Drawing;
using System.Web.UI.WebControls;
using Module.Core.LoginSystem.Commons;
using Module.Core.LoginSystem.Commons.Framwork;
using Module.Core.LoginSystem.Commons.Utilities;
using Module.Core.LoginSystem.Components.Audits;
using Module.Core.LoginSystem.Components.Commands;
using Module.Core.LoginSystem.Components.Modules;
using Module.Core.LoginSystem.Components.Roles;
using Module.Core.LoginSystem.Components.Users;

namespace Web.Cms.Users
{
    public partial class UserManagement : AdminUserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ArrayList _arrAlpha = new ArrayList();
                for (char _c = 'A'; _c <= 'Z'; _c++)
                {
                    _arrAlpha.Add(_c.ToString());
                }
                _arrAlpha.Add("All");
                rptAlpha.DataSource = _arrAlpha;
                rptAlpha.ItemDataBound += new RepeaterItemEventHandler(rptAlpha_ItemDataBound);
                rptAlpha.DataBind();
            }
        }

        protected void rptAlpha_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                string _alpha = (string)e.Item.DataItem;
                HyperLink _lnkAlpha = (HyperLink)e.Item.FindControl("lnkAlpha");
                _lnkAlpha.Text = _alpha;
                if (_alpha == "All") _alpha = string.Empty;
                string _url = Request.RawUrl;
                if (Request.QueryString["alpha"] != null)
                {
                    _url = _url.Replace("&alpha=" + Request.QueryString["alpha"], "&alpha=" + _alpha);
                    if (Request.QueryString["alpha"].ToString() == _alpha) _lnkAlpha.Attributes.Add("style", "text-decoration:underline;");
                }
                else if (_alpha != string.Empty)
                    _url = _url + "&alpha=" + _alpha;
                _lnkAlpha.NavigateUrl = _url;

            }
        }

        protected void grdUsers_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int _userId = ConvertUtility.ToInt32(e.CommandArgument);
            UserInfo _userInfo = UserController.GetUser(_userId);
            ModuleInfo _moduleInfo = ModuleController.GetModule(CurrentCommand.CtrlKey);
            switch (e.CommandName)
            {

                case "editprofile":
                    {
                        // Insert Cores_Audits
                        AuditController.CreateAuditQ(_moduleInfo.ModuleDefID, (int)AuditCode.View, CurrentCommand.CtrlKey, CurrentUser.UserID, _userId
                                                    , _userInfo.Username, 1, DateTime.Now);
                        //End
                        Response.Redirect(UIProcess.GetCPPage(CurrentPortalID, "admin_userprofile", new string[] { "tabkey", "userid" }, new string[] { "admin_usermanager", e.CommandArgument.ToString() }));
                        break;
                    }


                case "resetpassword":

                    // Insert Cores_Audits
                    AuditController.CreateAuditQ(_moduleInfo.ModuleDefID, (int)AuditCode.View, CurrentCommand.CtrlKey, CurrentUser.UserID, _userId
                                                , _userInfo.Username, 1, DateTime.Now);
                    //End
                    Response.Redirect(UIProcess.GetCPPage(CurrentPortalID, "admin_userpassword", new string[] { "tabkey", "userpasswordid" },
                                                          new string[] { "admin_usermanager", e.CommandArgument.ToString() }));

                    break;
                case "setrole":
                    // Insert Cores_Audits
                    AuditController.CreateAuditQ(_moduleInfo.ModuleDefID, (int)AuditCode.View, CurrentCommand.CtrlKey, CurrentUser.UserID, _userId
                                                , _userInfo.Username, 1, DateTime.Now);
                    //End
                    Response.Redirect(
                        UIProcess.GetCPPage(CurrentPortalID, "admin_setuserrole", new string[] { "tabkey", "userinroleid" },
                                            new string[] { "admin_usermanager", e.CommandArgument.ToString() }));

                    break;
                case "Userzones":
                    // Insert Cores_Audits
                    AuditController.CreateAuditQ(_moduleInfo.ModuleDefID, (int)AuditCode.View, CurrentCommand.CtrlKey, CurrentUser.UserID, _userId
                                                , _userInfo.Username, 1, DateTime.Now);
                    //End
                    Response.Redirect(
                      UIProcess.GetCPPage(CurrentPortalID, "admin_UserRoleZones", new string[] { "tabkey", "userinroleid" },
                                          new string[] { "admin_UserRoleZones", e.CommandArgument.ToString() }));

                    break;
                case "deleteuser":
                    try
                    {
                        if (UserController.CheckExistdUserInTable(_userId, "CMS_Contents", "CreatedBy") > 0
                            //|| UserController.CheckExistdUserInTable(_userId, "Advertisements", "CreatedBy") > 0
                            //|| UserController.CheckExistdUserInTable(_userId, "Adv_Customers", "CreatedBy") > 0
                            // || UserController.CheckExistdUserInTable(_userId, "Adv_Customers", "ModifiedBy") > 0                        
                            || UserController.CheckExistdUserInTable(_userId, "CMS_Contents", "ModifiedBy") > 0
                            || UserController.CheckExistdUserInTable(_userId, "CMS_Zones", "CreatedBy") > 0
                            )
                        {
                            lblError.Text = "<b style='color:black'>Bạn không được xóa Username: </b><b style='color:red'>" + _userInfo.Username + "</b><b>. Vì Username này đang hoạt động trên hệ thống!<b>";
                            return;
                        }
                        else
                        {
                            string _strUsername = _userInfo.Username;
                            UserController.RemoveUserFromPortal(ConvertUtility.ToInt32(e.CommandArgument.ToString()), CurrentPortalID);
                            List<UserInRoleInfo> lstRoles = RoleController.GetRolesForUser(ConvertUtility.ToInt32(e.CommandArgument));
                            foreach (UserInRoleInfo role in lstRoles)
                            {
                                UserController.RemoveUserFromRole(ConvertUtility.ToInt32(e.CommandArgument.ToString()), role.RoleID);
                            }
                            //GroupController.DeleteUserInGroup(ConvertUtility.ToInt32(e.CommandArgument));
                            UserController.DeleteUser(_userId);
                            // Insert Cores_Audits
                            AuditController.CreateAuditQ(_moduleInfo.ModuleDefID, (int)AuditCode.Delete, CurrentCommand.CtrlKey, CurrentUser.UserID, _userId
                                                        , _strUsername, 1, DateTime.Now);
                            //End
                            lblError.Text = MiscUtility.MSG_UPDATE_SUCCESS;
                        }

                    }
                    catch (Exception ex)
                    {
                        Response.Write(ex.Message);
                    }
                    break;
                default:
                    break;
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            string _keyword = txtKeyword.Text.Trim();
            string _searchBy = dropSearchBy.SelectedValue;
            string _alpha = ConvertUtility.ToString(Request.QueryString["alpha"]);
            List<UserInfo> _lstUsers = UserController.GetUsers(_keyword, _searchBy, _alpha);
            grdUsers.DataSource = _lstUsers;
            grdUsers.DataBind();

            CommandInfo _commandInfo = CommandController.GetCommand("admin_usermanager");
            RolePermisionInfo _roleInfo = RoleController.GetReadWritePermison(CurrentUser.UserID, _commandInfo.CommandID);
            if (_roleInfo == null) return;
            if (_roleInfo.Write == 0)
            {
                divAddUser.Visible = false;
                foreach (GridViewRow row in grdUsers.Rows)
                {
                    Button btnResetPassword = (Button)row.FindControl("btnResetPassword");
                    Button btnRole = (Button)row.FindControl("btnRole");
                    Button btnUserZones = (Button)row.FindControl("btnUserZones");
                    Button btnDelete = (Button)row.FindControl("btnDelete");

                    btnDelete.Enabled = false;
                    btnResetPassword.Enabled = false;
                    btnDelete.CssClass = "Icon_DeleteOff";
                    btnResetPassword.CssClass = "Icon_KeyOff";
                    btnRole.CssClass = "Icon_GroupOff";
                    btnRole.Enabled = false;
                }
            }
        }

        protected void grdUsers_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                UserInfo _user = (UserInfo)e.Row.DataItem;
                Label lblSTT = (Label)e.Row.FindControl("lblSTT");
                lblSTT.Text = Convert.ToString(e.Row.DataItemIndex + 1);
                Button btnResetPassword = (Button)e.Row.FindControl("btnResetPassword");
                Button btnRole = (Button)e.Row.FindControl("btnRole");
                //Button btnDelete1 = (Button)e.Row.FindControl("btnDelete");
                Button btnDelete = (Button)e.Row.FindControl("btnDelete");
                btnDelete.Attributes.Add("onclick", MiscUtility.DeleteConfirm("thành viên", _user.Username));

                if (_user.UserID == CurrentUser.UserID)
                {
                    btnResetPassword.Enabled = true;
                    btnRole.Enabled = true;
                    btnDelete.Enabled = false;
                    btnDelete.CssClass = "Icon_DeleteOff";
                }

            }
        }

        protected void grdUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grdUsers.PageIndex = e.NewPageIndex;
        }

        protected void lnkAddUser_Click(object sender, EventArgs e)
        {
            Response.Redirect(UIProcess.GetCPPage(CurrentPortalID, "admin_createuser", new string[] { "tabkey" }, new string[] { "admin_usermanager" }));
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect(UIProcess.DEFAULT_CP_PAGE);

        }
    }
}